package com.psnail.master.service.Impl;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.psnail.master.mapper.dao.UserDao;
import com.psnail.master.service.EmailService;
import com.psnail.tools.EmailTools;

@Service
public class EmailServiceImpl implements EmailService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private EmailTools ets;

	@Autowired
	private UserDao userDao;

	// 注册邮件发送的地址
	@Value("${email.address.zhuce}")
	private String zhuceAddress;

	// 修改密码邮件发送的地址
	@Value("${email.address.updatePasswordAddress}")
	private String updatePasswordAddress;

	@Override
	public Map<String, Object> zhuce(String email) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (email == null || "".equals(email)) {
			result.put("status", 0);
			result.put("message", "邮箱不能为空！");
		} else if (!ets.emailFormat(email)) {
			result.put("status", 0);
			result.put("message", "邮箱格式不正确！");
		} else {
			String title = "[蜗牛库]感谢注册，请验证邮箱" + email;
			String content = email + "：<br/>";
			content += "您好，感谢您注册蜗牛库，请点击下面的链接验证您的邮箱：<br/>";
			content += zhuceAddress + "?email=" + email;
			try {
				ets.sendEmail(email, title, content);
			} catch (Exception e) {
				logger.error("EmailServiceImpl/zhuce()发送邮件出现异常");
				result.put("status", 0);
				result.put("message", "邮件发送失败！请联系站长。");
			}
			result.put("status", 1);
			result.put("message", "邮件发送成功！请注意查收。若您没有收到邮件，请一分钟后核对邮箱重新验证。");
		}
		return result;
	}

	@Override
	public Map<String, Object> updatePassword(String email) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (email == null || "".equals(email)) {
			result.put("status", 0);
			result.put("message", "邮箱不能为空！");
		} else if (!ets.emailFormat(email)) {
			result.put("status", 0);
			result.put("message", "邮箱格式不正确！");
		} else {
			String title = "[蜗牛库]忘记密码，修改邮箱密码";
			String content = email + "：<br/>";
			content += "您好，请点击下面的链接设置新的密码：<br/>";
			content += updatePasswordAddress + "?id="
					+ userDao.selectByEmail(email).getId();
			try {
				ets.sendEmail(email, title, content);
			} catch (Exception e) {
				logger.error("EmailServiceImpl/updatePassword()发送邮件出现异常");
				result.put("status", 0);
				result.put("message", "邮件发送失败！请联系站长。");
			}
			result.put("status", 1);
			result.put("message", "邮件发送成功！请注意查收。若您没有收到邮件，请一分钟后核对邮箱重新操作。");
		}
		return result;
	}

}